package com.qf.smsplatform.executor;

import com.qf.smsplatform.client.CacheClient;
import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.Strategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 *  执行策略链
 */
@Component
@Slf4j
public class StrategyExecutor {


    @Autowired
    //1. 获取到全部的策略对象
    private Map<String, Strategy> strategies;

    @Autowired
    private CacheClient cacheClient;



    public void execute(StandardSubmit submit){
        log.info("【策略模块-StrategyExecutor】 准备开始执行策略链！");
        //2. 和Cache模块交互,获取客户信息中的filters
        String filters = cacheClient.hGet(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "filters");
        //  "phase,black,dirtyWord,limitFiveMinutes,limitOneHour,limitOneDay,fee,router"
        //3. 根据filters将全部的策略对象进行筛选和排序并依次执行
        if(!StringUtils.isEmpty(filters)){
            for (String s : filters.split(",")) {
                // 获取到指定的策略对象
                Strategy strategy = strategies.get(s);
                //4. 返回true,代表当前策略执行成功,继续执行后续策略,返回false,代表策略执行失败.
                if(!strategy.strategy(submit)){
                    break;
                }
            }
        }

        log.info("【策略模块-StrategyExecutor】 执行完毕全部策略链！");
    }

}
